package com.jeect.userservice3.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeect.userservice3.util.ResponseBody;
import com.jeect.userservice3.util.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String s = objectMapper.writeValueAsString(authentication);
        System.out.println(s);

        response.setContentType("application/json;charset=UTF-8");
        ResponseBody body;
        if(authentication.isAuthenticated()) {
            body = new ResponseBody(ResponseCode.SUCCESS, authentication.getPrincipal());
        }else{
            body=new ResponseBody(ResponseCode.FAILE,"认证失败!用户名、密码或验证码错误.");
        }
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(body));
    }
}
